package com.easylinkin.linkappapi.keywork.controller;


import cn.hutool.poi.word.Word07Writer;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.easylinkin.linkappapi.common.model.RequestModel;
import com.easylinkin.linkappapi.common.service.OSSService;
import com.easylinkin.linkappapi.keywork.utils.CreateSafeTableTreeUtils;
import com.easylinkin.linkappapi.keywork.utils.EntityCheckUtils;
import com.easylinkin.linkappapi.keywork.dto.SafeTableDto;
import com.easylinkin.linkappapi.keywork.dto.SafeTableTreeDto;
import com.easylinkin.linkappapi.keywork.entity.KeyworkList;
import com.easylinkin.linkappapi.keywork.entity.SafeTable;
import com.easylinkin.linkappapi.keywork.entity.SafeTableItem;
import com.easylinkin.linkappapi.keywork.service.KeyworkListService;
import com.easylinkin.linkappapi.keywork.service.SafeTableItemService;
import com.easylinkin.linkappapi.keywork.service.SafeTableService;
import com.easylinkin.linkappapi.keywork.utils.WordTableExportUtil;
import com.easylinkin.linkappapi.keywork.vo.SafeTableItemVo;
import com.easylinkin.linkappapi.keywork.vo.SafeTableRecordVo;
import com.easylinkin.linkappapi.keywork.vo.SafeTableTreeVo;
import com.easylinkin.linkappapi.keywork.vo.SafeTableVo;
import com.easylinkin.linkappapi.penetsecuremanage.dto.RailLinkappGridManagementInfoDTO;
import com.easylinkin.linkappapi.penetsecuremanage.service.IRailLinkappGridManagementInfoService;
import com.easylinkin.linkappapi.penetsecuremanage.vo.RailLinkappGridManagementInfoVO;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import site.morn.rest.RestBuilders;
import site.morn.rest.RestMessage;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.rmi.MarshalledObject;
import java.time.LocalDate;
import java.util.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 */
@RestController
@RequestMapping("/safeTable")
public class SafeTableController {

    @Autowired
    private SafeTableItemService safeTableItemService;

    @Autowired
    private IRailLinkappGridManagementInfoService railLinkappGridManagementInfoService;

    @Autowired
    private SafeTableService safeTableService;

    @Autowired
    private KeyworkListService keyworkListService;

    @Autowired
    private OSSService ossService;


    @PostMapping("/findTableItem")
    @ApiOperation("查询安全确认表字段")
    public RestMessage findTableItem(@RequestBody SafeTableItem safeTableItem) {
        List<SafeTableItemVo> record = safeTableItemService.selectList(safeTableItem);
        return RestBuilders.successBuilder(record).build();
    }


    @PostMapping("/addTable")
    @ApiOperation("新增安全确认表")
    public RestMessage addTable(@RequestBody SafeTable safeTable){
        String checkString = EntityCheckUtils.checkSafeTable(safeTable);
        if (null != checkString) {
            return RestBuilders.failureMessage(checkString);
        }
        if (safeTableService.addTable(safeTable)){
            return RestBuilders.successMessage();
        } else {
            return RestBuilders.failureMessage();
        }

    }

    @PostMapping("/selectTableList")
    @ApiOperation("查询安全确认表")
    public RestMessage selectTableList(@RequestBody SafeTable safeTable){
        List<SafeTableVo> safeTableVoList = safeTableService.selectList(safeTable);
        return RestBuilders.successBuilder(safeTableVoList).build();
    }

    @PostMapping("/selectTablePage")
    @ApiOperation("查询安全确认表")
    public RestMessage selectTablePage(@RequestBody RequestModel<SafeTable> requestModel){
        Assert.notNull(requestModel.getCustomQueryParams(), "customQueryParams 不能为空");
        Assert.notNull(requestModel.getPage(), "page 不能为空");
        IPage<SafeTableVo> record = safeTableService.selectPage(requestModel.getPage(), requestModel.getCustomQueryParams());
        return RestBuilders.successBuilder(record).build();
    }


    @PostMapping("/fillTable")
    @ApiOperation("填写写安全确认表")
    public RestMessage fillTable(@RequestBody SafeTableDto safeTableDto){
        //总表检查确认
        SafeTable safeTable = new SafeTable();
        safeTable.setId(safeTableDto.getId());
        SafeTableVo safeTableVo = safeTableService.selectList(safeTable).get(0);
        if (null == safeTableVo){ //校验传回的id对应的总表是否存在
            return RestBuilders.failureBuilder("500","安全条件确认表未找到").build();
        }
        List<SafeTableRecordVo> recordVoList = safeTableVo.getSafeTableRecordVoList();
        if (recordVoList.size() == 0){  //校验总表生成的检查记录是否存在
            return RestBuilders.failureBuilder("500","安全条件确认表检查项" +
                    "未找到").build();
        }


        //分三种情况
        //1协作人填写表格检查项但未选择确认人
        if (safeTableVo.getTableStatus() == 0 && null == safeTableDto.getCheckUserId()){ //此时前端仅提交了子项列表,总表仅更新最近修改时间
            safeTableDto.setLatestModifyTime(new Date());
            //2协作人员填写表格，并且选择了确认人
        }else if (null != safeTableDto.getCheckUserId() && safeTableVo.getTableStatus() == 0){//此时前端提交了确认人，总表更新确认人、最近修改时间、状态由0协作中改为1待签字
            safeTableDto.setTableStatus(1); //状态改为待签字，表格不可修改，仅可确认
            safeTableDto.setLatestModifyTime(new Date());
            safeTableDto.setPreSignTime(new Date()); //表格提交签字时间，用于考核查询
        //3表格确认人填写总表检查结果、备注、签名等内容
        } else if (StringUtils.isNotEmpty(safeTableDto.getCheckUserSign()) && safeTableDto.getCheckOpinion() != 0){
            safeTableDto.setTableStatus(2); //状态改为已完成
            safeTableDto.setCheckTime(new Date()); //确认时间
            safeTableDto.setLatestModifyTime(new Date());
            String path = ossService.saveImgBase64(safeTableDto.getCheckUserSign(),safeTableVo.getTableName()+"签名"); //将前端传过来的base64字符串转成图片，存放到服务器并返回路径
            if (path.contains("linkapp/linkapp/")){ //返回的路径中有重复路径，这里为了不影响全局，进行去重处理
                path = path.replace("linkapp/linkapp/","linkapp/");

            }
            safeTableDto.setCheckUserSign(path);
        }
        //更新主表
        if (safeTableService.updateTable(safeTableDto) != 1){
            return RestBuilders.failureBuilder("500","检查项确认失败").build();
        }

        if (null != safeTableDto.getSafeTableRecordDtoList() && safeTableDto.getSafeTableRecordDtoList().size() > 0) { //更新子项

            if (safeTableService.updateTableRecord(safeTableDto.getSafeTableRecordDtoList()) != 1){
                return RestBuilders.failureBuilder("500","检查项提交失败").build();
            }
        }
        return RestBuilders.successBuilder().build();
    }


    @PostMapping("/getSafeTableTree")
    @ApiOperation("查询安全确认表下拉树")
    public RestMessage getSafeTableTree(@RequestBody SafeTableTreeDto safeTableTreeDto){
        List<SafeTableTreeVo> safeTableTreeVoList = new ArrayList<>();
        //下拉结构分四层：网格、分类、作业、表格
        RailLinkappGridManagementInfoDTO dto = new RailLinkappGridManagementInfoDTO();
        List<RailLinkappGridManagementInfoVO> gridList  = railLinkappGridManagementInfoService.getList(dto);
        if (gridList.size() == 0) { //没有显示三层
            safeTableTreeVoList = CreateSafeTableTreeUtils.createSafeTableTree(keyworkListService,safeTableService, null);

        } else { //有网格信息显示四层
            for (RailLinkappGridManagementInfoVO grid:gridList){
                SafeTableTreeVo vo = new SafeTableTreeVo();
                vo.setTitle(grid.getGridName());
                vo.setId(grid.getId().toString());
                vo.setDataType("grid");
                vo.setExpand(true);
                vo.setSafeTableTreeVoList(CreateSafeTableTreeUtils.createSafeTableTree(keyworkListService,safeTableService, grid.getId()));

                safeTableTreeVoList.add(vo);
            }
        }


        return RestBuilders.successBuilder(safeTableTreeVoList).build();
    }


    @GetMapping("/exportWordReport/{tableId}")
    public void exportWordReport(HttpServletResponse response, Long tableId) throws IOException {

        SafeTable safeTable = new SafeTable();
        safeTable.setId(tableId);
        SafeTableVo safeTableVo = safeTableService.selectList(safeTable).get(0);
        List<SafeTableRecordVo> recordVoList = safeTableVo.getSafeTableRecordVoList();

        // 1. 准备表头（2行）
        List<Map<Integer, String>> headerRows = new ArrayList<>();

        // 标题行（合并所有列）
        Map<Integer, String> titleRow = new HashMap<>();
        titleRow.put(0, safeTableVo.getTableTitle());
        headerRows.add(titleRow);

        // 列标题行
        Map<Integer, String> colHeader = new HashMap<>();
        colHeader.put(0, "检查内容");
        colHeader.put(1, "检查内容");
        colHeader.put(2, "控制要求");
        colHeader.put(3, "检查结果");
        colHeader.put(4, "检查人");
        headerRows.add(colHeader);

        // 2. 准备数据（从数据库查询）

//        List<Map<Integer, String>> dataRows = getAttendanceData();
        List<Map<Integer, String>> dataRows = new ArrayList<>();
        for (SafeTableRecordVo vo : recordVoList){
            Map<Integer, String> row = new HashMap<>();
            row.put(0,vo.getCheckContent());
            row.put(1,vo.getCheckRequire());
            row.put(2,vo.getCheckRequireIntro());
            if (vo.getSubCheckResult() == 1){
                row.put(3, "☑是 □否");
            } else if (vo.getSubCheckResult() == -1){
                row.put(3, "□是 ☑否");

            } else {
                row.put(3, "□是 □否");
            }
            row.put(4,vo.getSubCheckUserName());
            dataRows.add(row);
        }
        Map<Integer, String> footerMap = new HashMap<>();
        footerMap.put(0, "检查意见");
        if (safeTableVo.getCheckOpinion() == 1){
            footerMap.put(1,"☑符合要求,同意  □不同意");

        } else if (safeTableVo.getCheckOpinion() == -1){
            footerMap.put(1,"□符合要求,同意  ☑不同意");

        } else {
            footerMap.put(1,"□符合要求,同意  □不同意");
        }
        dataRows.add(footerMap);

//        // 3. 准备表尾（1行）
//        List<Map<Integer, String>> footerRows = new ArrayList<>();
//        Map<Integer, String> footer = new HashMap<>();
//        footer.put(0, "检查意见");
//        if (safeTableVo.getCheckOpinion() == 1){
//            footer.put(1,"☑符合要求,同意  □不同意");
//
//        } else if (safeTableVo.getCheckOpinion() == -1){
//            footer.put(1,"□符合要求,同意  ☑不同意");
//
//        } else {
//            footer.put(1,"□符合要求,同意  □不同意");
//        }
//        footerRows.add(footer);

        // 4. 设置合并区域 [起始行,结束行,起始列,结束列]
        List<int[]> mergeRegions = new ArrayList<>();
//        mergeRegions.add(new int[]{0,0, 0, 4}); // 合并标题行
        mergeRegions.add(new int[]{1,1, 1, 5}); // 合并标题行
        mergeRegions.add(new int[]{3,4, 0, 0}); //
        mergeRegions.add(new int[]{5,6, 0, 0}); //
        mergeRegions.add(new int[]{8,9, 0, 0}); //
        mergeRegions.add(new int[]{10,11, 0, 0}); //
        mergeRegions.add(new int[]{12,13, 0, 0}); //
        mergeRegions.add(new int[]{12,13, 0, 0}); //
        mergeRegions.add(new int[]{16,16, 2, 5}); //

        mergeRegions.add(new int[]{dataRows.size()+1, dataRows.size()+2, 1, 4}); // 合并表尾部分列

        // 5. 导出Word
        WordTableExportUtil.exportWordTable(response,"安全条件确认表",headerRows,dataRows,
                null,mergeRegions);
    }

//
//    @GetMapping("/exportWordReport/{tableId}")
//    public void exportWordReport(HttpServletResponse response, Long tableId) throws IOException {
//
//        // 表头
//        List<List<String>> header =Collections.singletonList(Arrays.asList("高墩身拆模作业安全条件确认表"));
//        // 数据（可从数据库查询）
//        List<List<String>> data = Arrays.asList(
//                Arrays.asList("检查内容", "控制要求","控制要求", "检查结果", "检查人"),
//                Arrays.asList("作业许可证", "证件", "是否办理动火作业许可证；" +
//                        "是否办理高处作业许可证；" +
//                        "是否办理吊装作业许可证", "是  否"),
//                Arrays.asList("汽车吊", "相关证件", "确认汽车吊和人员巳报批，定期维保", "是  否"),
//                Arrays.asList("汽车吊", "安全装置", "设备运行正常，限载、限位装置等工作状态正常", "是  否")
//        );
//        // 合并配置：第0行第0-1列横向合并，第1-2行第2列纵向合并
//        List<WordTableExportUtil.MergeConfig> mergeConfigs = Arrays.asList(
//                new WordTableExportUtil.MergeConfig(0, 0, 0, 4), // 横向合并
//
//                new WordTableExportUtil.MergeConfig(2, 2, 1, 2),  // 纵向合并
//                new WordTableExportUtil.MergeConfig(3, 4, 0, 0)  // 纵向合并
//        );
//
//        byte[] wordBytes = WordTableExportUtil.exportWordTable(header, data, mergeConfigs);
//
//        String fileName = URLEncoder.encode("导出表格.docx", "UTF-8");
//        response.setContentType("application/octet-stream");
//        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
//        response.getOutputStream().write(wordBytes);
//        response.getOutputStream().flush();
//    }
}
